import GCConnection from "../../GCConnection";
import { ILeaderboardItem } from "../../model/model-account";
import BaseWindow from "../common-components/BaseWindow";
import GCBlock from "../common-components/GCBlock";
import GCToast from "../common-components/GCToast";
import LeaderboardItemComp from "./LeaderboardItemComp";


const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('wnds/LeaderboardComp')
export default class LeaderboardComp extends BaseWindow {

    @property(cc.ScrollView)
    listview: cc.ScrollView = null;

    @property(cc.Node)
    ItemTemplate: cc.Node = null;

    @property(cc.Label)
    meRankLbl: cc.Label = null;
    @property(cc.Sprite)
    meIconSpr: cc.Sprite = null;
    @property(cc.Label)
    meScoreLbl: cc.Label = null;

    private _list: LeaderboardItemComp[] = [];

    protected onEnable(): void {
        super.onEnable();

        this.doRequest();
    }

    async doRequest() {
        GCBlock.block();
        try {
            const res = await GCConnection.requestLeaderboard();
            if (!cc.isValid(this.node)) return;

            this.initUI(res.me, res.list);

        } catch (e) {
            cc.error(e);

            GCToast.toast(`更新排行榜失败`);
        } finally {
            GCBlock.unblock();
        }
    }

    initUI(me: ILeaderboardItem, list: ILeaderboardItem[]) {
        this.initMe(me);
        this.initList(list);
    }

    initList(list: ILeaderboardItem[]) {
        this._list.length = 0;
        this.listview.content.removeAllChildren();

        for (let i = 0; i < list.length; i++) {

            const data = list[i];
            const node = cc.instantiate(this.ItemTemplate);
            const comp = node.getComponent(LeaderboardItemComp);

            node.active = true;
            this.listview.content.addChild(comp.node);
            comp.initUI(data);

            this._list.push(comp);
        }
    }

    updateList(list: any[]) {
        for (let i = 0; i < list.length; i++) {

            const data = list[i];
            const comp = this._list[i];

            comp.updateUI(data);
        }
    }

    initMe(res: ILeaderboardItem) {
        this.updateMe(res);
    }

    updateMe(res: ILeaderboardItem) {
        if (res.rank == -1) {
            this.meRankLbl.string = `Ranking:  >100`;
        } else {
            this.meRankLbl.string = `Ranking:  ${res.rank}`;
        }
        // this.meIconSpr.spriteFrame = 
        this.meScoreLbl.string = res.hearts + '';
    }

    onShareBtnClicked() {

    }
}
